/**
 * @title 区间盈亏
 */
import React, { PureComponent } from 'react';
import { Row, Col, message, Spin } from 'antd';
import { connect } from 'dva';
import { SecondHeaderC, QuickQueryC, XYAxisChartsC } from '../../../../../comps';
import { getUserInfo } from '../../../../../utils/commonFunc';

@connect(({ profitAndLossAnalysisM }) => ({
  profitAndLossAnalysisM,
}))
class IntervalProitAndLoss extends PureComponent {
  state = {
    // radioVal: 'month', 默认值时会触发onchange时间发生请求，实际在didmount里会根据业务需要进行设置日月年快捷键，所以这里不去掉
    ranking: {},
    trend: {},
    disabledValue: [],
    loading: false,
    isSuper: false,
  };

  componentDidMount() {
    const {
      searchData: { beginDate, endDate },
    } = this.props;
    this.getD(beginDate, endDate);
    const isSuper = getUserInfo();
    this.setState({
      isSuper: isSuper.isSuper,
    });
  }

  // 判断日期是否大于一个月
  getD = (startdate, enddate) => {
    let type = '';
    const { searchData } = this.props;
    const startD = new Date(Date.parse(searchData.beginDate.replace(/-/g, '/')));
    const endD = new Date(Date.parse(searchData.endDate.replace(/-/g, '/')));
    const days = parseInt((endD.getTime() - startD.getTime()) / (1000 * 60 * 60 * 24));

    const datas = {
      ...searchData,
    };
    if (days >= 365) {
      type = 'month';
      datas.IntervalDimension = 'month';
      this.setState(
        {
          radioVal: type,
          disabledValue: [],
        },
        () => {
          this.getData(datas);
        },
      );
    } else if (days > 30 && days < 365) {
      type = 'month';
      datas.IntervalDimension = 'month';
      this.setState(
        {
          radioVal: 'month',
          disabledValue: ['year'],
        },
        () => {
          this.getData(datas);
        },
      );
    } else if (days <= 30) {
      type = 'day';
      datas.IntervalDimension = 'day';
      this.setState(
        {
          radioVal: 'day',
          disabledValue: ['month', 'year'],
        },
        () => {
          this.getData(datas);
        },
      );
    }
  };

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.searchData) !== JSON.stringify(this.props.searchData)) {
      if (nextProps && nextProps.searchData.portfolioCode) {
        this.setState({
          ranking: {},
          // trend: {},
        });
        const datas = {
          ...nextProps.searchData,
        };
        const startD = new Date(Date.parse(nextProps.searchData.beginDate.replace(/-/g, '/')));
        const endD = new Date(Date.parse(nextProps.searchData.endDate.replace(/-/g, '/')));
        const days = parseInt((endD.getTime() - startD.getTime()) / (1000 * 60 * 60 * 24));
        if (days >= 365) {
          datas.IntervalDimension = 'month';
          this.setState(
            {
              radioVal: 'month',
              disabledValue: [],
            },
            () => {
              this.getData(datas);
            },
          );
        } else if (days > 30 && days < 365) {
          datas.IntervalDimension = 'month';
          this.setState(
            {
              radioVal: 'month',
              disabledValue: ['year'],
            },
            () => {
              this.getData(datas);
            },
          );
        } else if (days <= 30) {
          datas.IntervalDimension = 'day';
          this.setState(
            {
              radioVal: 'day',
              disabledValue: ['month', 'year'],
            },
            () => {
              this.getData(datas);
            },
          );
        }
      }
    }
  }

  // 查询
  getData = (args) => {
    this.setState({
      loading: true,
    });
    this.props.dispatch({
      type: 'profitAndLossAnalysisM/getEchartDate1',
      payload: { ...args },
      callback: (res) => {
        this.setState({
          loading: false,
        });
        const { data } = res;
        if (res.code == 0) {
          this.setState({
            ranking: data.ranking || {},
            trend: data.trend || {},
          });
        } else {
          message.error(res.msg);
          this.setState({
            ranking: {},
            trend: {},
          });
        }
      },
    });
  };

  // 按钮点击事件
  onChangeRadio = (e) => {
    const { searchData } = this.props;

    if (e !== undefined) {
      this.setState({
        radioVal: e,
      });
      this.getData({
        ...searchData,
        IntervalDimension: e,
      });
    }
  };

  render() {
    const { trend, radioVal, disabledValue, loading, isSuper } = this.state;
    // 保存年月日切换数据
    sessionStorage.setItem('changeDMY', radioVal);
    const { colorType } = this.props;
    const xAxis = trend.xAxis || [];
    const series = trend.series || [];

    return (
      <div style={{ width: '100%' }}>
        <SecondHeaderC title='区间盈亏' colorType={colorType} />
        <Row>
          <Col span={24} style={{ textAlign: 'right' }}>
            <QuickQueryC
              dataSource={[
                { value: 'day', title: '日' },
                { value: 'month', title: '月' },
                { value: 'year', title: '年' },
              ]}
              initialValue={radioVal}
              disabled={isSuper ? [] : disabledValue}
              onChange={(e) => this.onChangeRadio(e)}
            />
          </Col>
        </Row>
        <div style={{ marginTop: '10px' }}>
          <Spin spinning={loading}>
            <XYAxisChartsC
              series={series}
              xAxis={xAxis}
              height={378}
              dataZoom={true}
              gridLeft={90}
              gridRight={20}
              yAxisUnit={['单位(万元)']}
              debtAndProfit={true}
              seriesLabelDataFormat={radioVal == 'day' || !this.state.isSuper ? [] : [(params) => params.data?.value]}
              type='bar'
              colorType={colorType}
            />
          </Spin>
        </div>
      </div>
    );
  }
}
export default IntervalProitAndLoss;
